namespace AutoTest.Core.FileSystem
{
    using System.IO;
    using Messaging;

    public class DirectoryWatcher : IDirectoryWatcher
    {
        readonly IMessageBus _bus;
        readonly FileSystemWatcher _watcher;

        public DirectoryWatcher(IMessageBus bus)
        {
            _bus = bus;
            _watcher = new FileSystemWatcher
                           {
                               NotifyFilter = NotifyFilters.LastWrite,
                               IncludeSubdirectories = true,
                               Filter = "*.*",
                           };

            _watcher.Changed += WatcherChangeHandler;
            _watcher.Created += WatcherChangeHandler;
        }

        void WatcherChangeHandler(object sender, FileSystemEventArgs e)
        {
            _bus.Publish(new FileChangeMessage(new FileInfo(e.FullPath)));
        }

        public void Watch(string path)
        {
            _watcher.Path = path;
            _watcher.EnableRaisingEvents = true;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            _watcher.Dispose();
        }
    }
}